package com.zyf.chapter02.structure.decorator.eureka;

import java.util.concurrent.atomic.AtomicReference;

/**
 *
 * @author yifeng
 */
public class SessionedHttpClient extends HttpClientDecorator {

    HttpClientFactory clientFactory;

    AtomicReference<HttpClient> httpClientRef = new AtomicReference<>();

    SessionedHttpClient(HttpClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    protected String execute(RequestExecutor executor) {
        System.out.println("sessioned 执行 execute 逻辑");
        if (httpClientRef.get() == null) {
            httpClientRef.set(clientFactory.newClient());
        }
        return executor.execute(httpClientRef.get());
    }

    // 这个方法会把一部分行为委托给 delegate
    @Override
    public String getApplications() {
        return execute(new RequestExecutor() {
            @Override
            public String execute(HttpClient delegate) {
                return delegate.getApplications();
            }
        });
    }
}
